import axios from "axios";
import { api } from './api';
import router from '../../router';
import { Toast } from "vant";
function initLogin() {
  axios.defaults.withCredentials = true;
  axios({
    method: "post",
    url: api.user.checkLogin,
    xsrfCookieName: true
  }).then((response) => {
    var res = response.data;
    if (res.code) {
      try {
        if (localStorage.getItem("Now_User") != null) {
          localStorage.removeItem("Now_User");
        }
        localStorage.setItem("Now_User", JSON.stringify(res.data));
      } catch (e) {

      }
      return true;
    } else {
      var rememberPassword = localStorage.getItem("Remember_Pssword"); // Cookies.get("Remember_Pssword");
      if (rememberPassword == null) {
        router.push({ path: '/login' });
      } else {
        var loginData = JSON.parse(rememberPassword);
        axios({
          method: 'post',
          url: api.user.login,
          data: loginData
        }).then((login) => {
          var loginRes = login.data;
          if (loginRes.code) {
            if (localStorage.getItem("Now_User") != null) {
              localStorage.removeItem("Now_User");
            }
            localStorage.setItem("Now_User", JSON.stringify(loginRes.data));
            Toast(loginRes.msg);
            return true;
          } else {
            Toast(loginRes.msg);
            router.push({ path: '/login' });
          }
        });
      }
    }
  });
}

function layout() {
  axios({
    method: 'post',
    url: api.user.layout
  }).then((res) => {
    var res = res.data;
    if (res.code) {
      Toast(res.msg);
      if (localStorage.getItem("Now_User") != null) {
        localStorage.removeItem("Now_User");
      }
      router.push({ path: '/login' });
      return true;
    }
    Toast(res.msg);
  });

}
export {
  initLogin,
  layout
}